package com.dhms.uikit

import android.content.Context
import android.content.DialogInterface
import android.view.LayoutInflater
import com.dhms.uikit.databinding.TimeRangePickerViewBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import java.util.*

class TimeRangePicker(context: Context, val onTimeRangChanged: (timeRange: List<Date?>) -> Unit) :
    MaterialAlertDialogBuilder(context, R.style.Theme_UiKit_TimeRangePicker) {

    private lateinit var binding: TimeRangePickerViewBinding

    private var timePickStep = TimePickStep.START_DATE

    private var chosenTime = mutableMapOf<TimePickStep, String?>()

    init {
        init()
    }

    private fun init() {
        binding = TimeRangePickerViewBinding.inflate(LayoutInflater.from(context))

        setView(binding.root)

        setIs24HourView(true)

        // On DataPicker Changed
        binding.datePicker.setOnDateChangedListener { _, year, monthOfYear, dayOfMonth ->
            val m = monthOfYear + 1
            val month = if (m >= 10) m.toString() else "0$m"
            val day = if (dayOfMonth >= 10) dayOfMonth.toString() else "0$dayOfMonth"
            val dateString = "$year-$month-$day"

            if (timePickStep == TimePickStep.START_DATE) {
                binding.chosenStartTime.text =
                    dateString + (if (chosenTime[TimePickStep.START_TIME] != null) " " + chosenTime[TimePickStep.START_TIME] else "")
                chosenTime[TimePickStep.START_DATE] = dateString
                timePickStep = TimePickStep.START_TIME
            } else if (timePickStep == TimePickStep.END_DATE) {
                binding.chosenEndTime.text =
                    dateString + (if (chosenTime[TimePickStep.END_TIME] != null) " " + chosenTime[TimePickStep.END_TIME] else "")
                chosenTime[TimePickStep.END_DATE] = dateString
                timePickStep = TimePickStep.END_TIME
            }
            binding.isTimePickerVisible = true
        }
        // On TimePicker Changed
        binding.timePicker.setOnTimeChangedListener { _, hourOfDay, minuteOfHour ->
            val hour = if (hourOfDay >= 10) hourOfDay.toString() else "0$hourOfDay"
            val minute = if (minuteOfHour >= 10) minuteOfHour.toString() else "0$minuteOfHour"
            val timeString = "$hour:$minute:00"

            if (timePickStep == TimePickStep.START_TIME) {
                val startTimeString = chosenTime[TimePickStep.START_DATE] + " " + timeString
                binding.chosenStartTime.text = startTimeString
                chosenTime[TimePickStep.START_TIME] = timeString
//                timePickStep = TimePickStep.END_DATE
//                binding.isTimePickerVisible = false
//                binding.isStartTimeSelected = false
            } else if (timePickStep == TimePickStep.END_TIME) {
                val endTimeString = chosenTime[TimePickStep.END_DATE] + " " + timeString
                binding.chosenEndTime.text = endTimeString
                chosenTime[TimePickStep.END_TIME] = timeString
            }
        }

        // On Start Time Clicked
        binding.chosenStartTime.setOnClickListener {
            timePickStep = TimePickStep.START_DATE
            binding.isTimePickerVisible = false
            binding.isStartTimeSelected = true
        }

        // On End Time Clicked
        binding.chosenEndTime.setOnClickListener {
            timePickStep = TimePickStep.END_DATE
            binding.isTimePickerVisible = false
            binding.isStartTimeSelected = false
        }

        binding.isStartTimeSelected = true
    }

    fun setTimeRange(timeRange: List<Date?>): TimeRangePicker {
        try {
            val startTime = timeRange[0]?.toFormatDate()
            chosenTime[TimePickStep.START_DATE] = startTime?.split(" ")?.get(0)
            chosenTime[TimePickStep.START_TIME] = startTime?.split(" ")?.get(1)
            binding.chosenStartTime.text = startTime
        } catch (e: Exception) {
        }
        try {
            val endTime = timeRange[1]?.toFormatDate()

            chosenTime[TimePickStep.END_DATE] = endTime?.split(" ")?.get(0)
            chosenTime[TimePickStep.END_TIME] = endTime?.split(" ")?.get(1)
            binding.chosenEndTime.text = endTime
        } catch (e: Exception) {
        }

        return this
    }

    fun setIs24HourView(is24HourView: Boolean) {
        binding.timePicker.setIs24HourView(is24HourView)
    }

    override fun setOnDismissListener(onDismissListener: DialogInterface.OnDismissListener?): MaterialAlertDialogBuilder {
        timePickStep = TimePickStep.START_DATE
        chosenTime.clear()

        return super.setOnDismissListener(onDismissListener)
    }

    fun showDialog() {
        val dialog = super.create()
        binding.dialogNegativeBtn.setOnClickListener {
            dialog.dismiss()
        }
        binding.dialogPositiveBtn.setOnClickListener {
            val startDate = chosenTime[TimePickStep.START_DATE]
            val endDate = chosenTime[TimePickStep.END_DATE]
            val timeRange = mutableListOf<Date?>()
            timeRange.add(
                0, if (startDate != null) {
                    val startTime = chosenTime[TimePickStep.START_TIME] ?: "00:00:00"
                    "$startDate $startTime".toDate()
                } else {
                    null
                }
            )
            timeRange.add(
                1, if (endDate != null) {
                    val endTime = chosenTime[TimePickStep.END_TIME] ?: "23:59:59"
                    "$endDate $endTime".toDate()
                } else {
                    null
                }
            )
            onTimeRangChanged(timeRange)
            dialog.dismiss()
        }

        dialog.show()
    }

    companion object {
        enum class TimePickStep {
            START_DATE,
            START_TIME,
            END_DATE,
            END_TIME
        }
    }
}